/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  CsszOwnerInfoActivity.java   
 * @Package com.jiyi.activity.cssz   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-5-19 下午2:09:38   
 * @version V1.0     
 */
package com.jiyi.activity.cssz;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.activity.Map_MyLocationActivity;
import com.jiyi.adapter.CommonAdapter;
import com.jiyi.adapter.ViewHolder;
import com.jiyi.bean.weibao.CsszOwnerInfoBean;
import com.jiyi.bean.weibao.CsszOwnerInfoBean.Data.BranchInfo;
import com.jiyi.bean.weibao.CsszOwnerInfoBean.Industry;
import com.jiyi.bean.weibao.CsszOwnerInfoBean.Supervision;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.DateChooseDialog;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DeviceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: CsszOwnerInfoActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-5-19 下午2:09:38
 * 
 */
public class CsszOwnerInfoActivity extends ActivityBase {

	@BindView(R.id.etOwnerName)
	EditText etOwnerName;
	@BindView(R.id.etAddress)
	EditText etAddress;
	@BindView(R.id.etPrincipal)
	EditText etPrincipal;
	@BindView(R.id.etFzTel)
	EditText etFzTel;
	@BindView(R.id.etFee)
	EditText etFee;
	@BindView(R.id.etExpireDate)
	EditText etExpireDate;
	@BindView(R.id.etStartDate)
	EditText etStartDate;
	@BindView(R.id.etTel)
	EditText etTel;

	@BindView(R.id.state_supervision)
	Spinner state_supervision;
	@BindView(R.id.state_industry)
	Spinner state_industry;

	// 定位事件
	final int LOCATION = 1;
	// 监管列表适配器
	CommonAdapter<Supervision> stateSupervisionAdapter;
	// 监管列表数据源
	List<Supervision> supervisionDataList = new ArrayList<Supervision>();
	// 行业列表适配器
	CommonAdapter<Industry> stateIndustryAdapter;
	// 行业列表数据源
	List<Industry> industryDataList = new ArrayList<Industry>();
	// 进度条
	Dialog dialog;
	// 经纬度
	String latitude, longitude;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cssz_owner_info);
		ButterKnife.bind(this);
		init();
	}
	
	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}

	/**
	 * @author: HYM
	 * @Title: init
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-5-19
	 */
	private void init() {
		setViewStatus();
		setTop("业主信息", "", getResources().getString(R.string.save), false,
				true, null, null);
		setAdapter();
		getData();
	}

	/**
	 * @author: HYM
	 * @Title: setViewStatus
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-5-19
	 */
	private void setViewStatus() {
		etStartDate.setKeyListener(null);
		etExpireDate.setKeyListener(null);
		// 设置必填项目验证
		etAddress.setTag(R.id.tag_view_empty, "联系地址不能为空");
		etOwnerName.setTag(R.id.tag_view_empty, "单位名称不能为空");

	}

	private void setAdapter() {

		stateSupervisionAdapter = new CommonAdapter<Supervision>(this,
				supervisionDataList, R.layout.item_state_small) {

			@Override
			public void convert(ViewHolder holder, Supervision t) {
				holder.setText(R.id.state_name, t.getName());
			}
		};
		state_supervision.setAdapter(stateSupervisionAdapter);

		stateIndustryAdapter = new CommonAdapter<Industry>(this,
				industryDataList, R.layout.item_state_small) {

			@Override
			public void convert(ViewHolder holder, Industry t) {
				holder.setText(R.id.state_name, t.getIndustry());
			}
		};
		state_industry.setAdapter(stateIndustryAdapter);
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("company_id", AppConfig.getSelectCompanyId() + "");

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.CSSZ_OWNER_DETAIL, "",
				params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								CsszOwnerInfoBean temp = new Gson().fromJson(
										result, CsszOwnerInfoBean.class);

								setIndustryInfo(temp.getData().getIndustry());
								setSupervisionInfo(temp.getData()
										.getGetSupervision());
								setOwnerInfo(temp.getData().getBranchInfo());

							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
							ToastUtil.getInstances().showMsg(e.getMessage());
						} finally {
							hideDialog(dialog);
						}

					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}

	/**
	 * @author: HYM
	 * @Title: doPost
	 * @Description: TODO(保存) void
	 * @date: 2017-5-19
	 */
	void doPost() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("ID", AppConfig.getSelectCompanyId() + "");
		params.put("keyword", etOwnerName.getText().toString());
		params.put("addr", etAddress.getText().toString());
		params.put("principal", etPrincipal.getText().toString());
		params.put("principal_tel", etFzTel.getText().toString());
		params.put("year_premium", etFee.getText().toString());
		params.put("expire_start_time", etStartDate.getText().toString());
		params.put("expire_time", etExpireDate.getText().toString());
		params.put("tel", etTel.getText().toString());
		params.put(
				"supervisedId",
				new Gson().fromJson(
						state_supervision.getSelectedItem().toString(),
						Supervision.class).getId());
		params.put(
				"industry",
				new Gson().fromJson(
						state_industry.getSelectedItem().toString(),
						Industry.class).getId());
		params.put("geo_lng", longitude);
		params.put("geo_lat", latitude);

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.CSSZ_OWNER_UPDATE, "",
				params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}

					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}

	/**
	 * @author: HYM
	 * @Title: setSupervisionInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param getSupervision
	 *            void
	 * @date: 2017-5-19
	 */
	protected void setSupervisionInfo(List<Supervision> getSupervision) {
		if (getSupervision.size() > 0) {
			supervisionDataList.clear();
			supervisionDataList.addAll(getSupervision);
			stateSupervisionAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * @author: HYM
	 * @Title: setIndustryInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param industry
	 *            void
	 * @date: 2017-5-19
	 */
	protected void setIndustryInfo(List<Industry> industry) {
		if (industry.size() > 0) {
			industryDataList.clear();
			industryDataList.addAll(industry);
			stateIndustryAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * @author: HYM
	 * @Title: setOwnerInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param branchInfo
	 *            void
	 * @date: 2017-5-19
	 */
	protected void setOwnerInfo(BranchInfo branchInfo) {
		etOwnerName.setText(branchInfo.getName());
		etAddress.setText(branchInfo.getAddress());
		etStartDate.setText(branchInfo.getExpire_start_time());
		etExpireDate.setText(branchInfo.getExpire_time());
		etFee.setText(branchInfo.getYear_premium());
		etFzTel.setText(branchInfo.getPrincipal_tel());
		etPrincipal.setText(branchInfo.getPrincipal());
		etTel.setText(branchInfo.getPhone());

		state_supervision.setSelection(getSupervisionById(branchInfo
				.getSupervised_id()));
		state_industry
				.setSelection(getIndustryById(branchInfo.getIndustry_id()));
		latitude = branchInfo.getGeo_lat();
		longitude = branchInfo.getGeo_lng();
	}

	int getSupervisionById(String id) {
		for (int i = 0; i < supervisionDataList.size(); i++) {
			Supervision supervision = supervisionDataList.get(i);
			if (supervision.getId().equals(id)) {
				return i;
			}
		}
		return 0;
	}

	int getIndustryById(String id) {
		for (int i = 0; i < industryDataList.size(); i++) {
			Industry industry = industryDataList.get(i);
			if (industry.getId().equals(id)) {
				return i;
			}
		}
		return 0;
	}

	@OnClick({ R.id.tvTitle, R.id.tvSearch, R.id.etExpireDate, R.id.ivLocation,R.id.etStartDate })
	public void onClick(View view) {
		Intent intent = null;
		DateChooseDialog.Builder builder;
		switch (view.getId()) {
		case R.id.tvTitle:
			finish();
			break;

		case R.id.tvSearch:
			// 保存
			if (CheckUtil.checkEditText(etOwnerName, etAddress)) {
				doPost();
			}
			break;
		case R.id.etStartDate:
			// 开始日期
			builder = new DateChooseDialog.Builder(this);
			builder.setTitle("选择日期");
			builder.setTextView(etStartDate);
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});

			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.create().show();

			break;
		case R.id.etExpireDate:
			// 开始日期
			builder = new DateChooseDialog.Builder(this);
			builder.setTitle("选择日期");
			builder.setTextView(etExpireDate);
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});

			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.create().show();

			break;
		case R.id.ivLocation:
			// 定位
			if (!DeviceUtil.getInstance().isGpsEnable()) {
				ToastUtil.getInstances().showMsg("请打开GPS定位");
				return;
			}
			
//			intent = new Intent(this, MapDisplayActivity.class);
//			startActivity(intent);
//			
			intent = new Intent(this, Map_MyLocationActivity.class);
			intent.putExtra("mapType", 1);
			intent.putExtra("latitude",latitude);
			intent.putExtra("longitude",longitude);
			intent.putExtra("address", etAddress.getText().toString());
			startActivityForResult(intent, LOCATION);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == LOCATION) {
			if (resultCode == RESULT_OK) {
				etAddress.setText(data.getStringExtra("address"));
				latitude = data.getStringExtra("latitude");
				longitude = data.getStringExtra("longitude");

			}
		}
	}
}
